<div class="layui-card layadmin-header">
  <div class="layui-breadcrumb" lay-filter="breadcrumb">
    <a><cite>活动管理</cite></a>
    <a lay-href="lottery/index">抽奖活动</a>
    <a><cite>抽奖活动编辑</cite></a>
  </div>
</div>

<div class="layui-fluid">
  <div class="layui-card" style="height: 1000px">
    <div class="layui-card-body" style="padding-top: 40px;">
      <div class="layui-carousel" id="stepForm" lay-filter="stepForm" style="margin: 0 auto;">
        <div carousel-item style="height: 1000px">
          <div>
            <form class="layui-form" style="margin: 20px auto;max-width: 700px;">
              <script type="text/html" template lay-url="agent-admin/lotteries/{{layui.router().search.id || 0}}"
                      lay-done="layui.data.done(d.data)">
                {{# var data = d.data || {} }}
                <div class="layui-form-item">
                  <label class="layui-form-label">活动名称</label>
                  <div class="layui-input-inline" style="width: 300px">
                    <input type="hidden" name="id" value="{{data.id || ''}}"/>
                    <input name="name" type="text" lay-verify="required" class="layui-input"
                           value="{{data.name || ''}}"/>
                  </div>
                </div>
                <div class="layui-form-item">
                  <div class="layui-inline">
                    <label class="layui-form-label">开始时间</label>
                    <div class="layui-input-inline">
                      <input type="text" id="start_time" class="layui-input" name="start_time" readonly
                             placeholder="请选择活动开始时间" lay-verify="required" autocomplete="off"
                             value="{{data.start_time || ''}}">
                    </div>
                  </div>
                  <div class="layui-inline">
                    <label class="layui-form-label">结束时间</label>
                    <div class="layui-input-inline">
                      <input type="text" id="end_time" class="layui-input" name="end_time" readonly
                             placeholder="请选择活动结束时间"
                             lay-verify="required" autocomplete="off" value="{{data.end_time || ''}}">
                    </div>
                  </div>
                </div>
                <div class="layui-form-item">
                  <label class="layui-form-label">活动说明</label>
                  <div class="layui-input-block">
                    <div id="description">{{data.description || ''}}</div>
                  </div>
                </div>
              </script>
              <div class="layui-form-item">
                <div class="layui-input-block">
                  <button class="layui-btn" lay-submit lay-filter="formStep1">
                    下一步
                  </button>
                </div>
              </div>
            </form>
          </div>
          <div>
            <form class="layui-form layui-form-pane" style="margin: 20px auto;max-width: 700px;">
              <div class="layui-form-item">
                <button id="btn_add_award" class="layui-btn layui-btn-sm">
                  <i class="layui-icon layui-icon-add-1"></i>添加奖品
                </button>
              </div>
              <div class="layui-form-item">
                <table id="lottery_awards" lay-filter="lottery_awards"></table>
                <script type="text/html" id="tpl_name">
                  {{d.name}}
                </script>
                <script type="text/html" id="tpl_rate">
                  {{d.rate}} %
                </script>
                <script type="text/html" id="tpl_user_limit">
                  {{d.user_limit > 0 ? d.user_limit : '不限' }}
                </script>
                <script type="text/html" id="tpl_tool">
                  <a class="layui-table-link layui-font-green" lay-event="edit">
                    <i class="layui-icon layui-icon-edit"></i>编辑
                  </a>
                  <div class="ant-divider"></div>
                  <a class="layui-table-link layui-font-red" lay-event="del">
                    <i class="layui-icon layui-icon-delete"></i>删除
                  </a>
                </script>
              </div>
              <div class="layui-form-item">
                <div class="layui-input-block">
                  <button type="button" class="layui-btn layui-btn-primary pre">上一步</button>
                  <button class="layui-btn" lay-submit lay-filter="formStep2">
                    保存
                  </button>
                  </script>
                </div>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<script>
  layui.data.done = function (lottery) {
    lottery = lottery || {}
    layui.use(['step', 'fox_upload', 'laydate', 'wangEditor'], function () {
      let $ = layui.$
        , form = layui.form
        , admin = layui.admin
        , step = layui.step
        , laydate = layui.laydate
        , table = layui.table
        , editor = layui.wangEditor
        , view = layui.view

      let form_data = {}

      step.render({
        elem: '#stepForm',
        filter: 'stepForm',
        width: '100%', //设置容器宽度
        stepWidth: '750px',
        height: '500px',
        stepItems: [{
          title: '活动基础信息'
        }, {
          title: '添加奖品'
        }]
      });

      form.render()

      //# STEP 1
      //日历初始化
      laydate.render({
        elem: '#start_time'
        , type: 'datetime'
      });
      laydate.render({
        elem: '#end_time'
        , type: 'datetime'
      });

      //编辑器
      editor.render({
        elem: "#description"
        , height: 300
        , name: 'description'
        , url: 'editor/images'
      });


      form.on('submit(formStep1)', function (data) {
        form_data = data.field
        if (!data.field.description) {
          layer.tips('请填写活动说明', $('#description'));
          return false;
        }
        form_data.description = data.field.description
        step.next('#stepForm')
        renderAwards()
        return false;
      });

      form.on('submit(formStep2)', function (data) {
        if (lottery.status && lottery.status.value === 'enabled') {
          layer.msg('活动开启状态下禁止编辑')
          return false
        }
        form_data.awards = Object.values(awards)
        if (form_data.awards.length == 0) {
          layer.msg('请添加至少一个奖品')
          return false;
        }
        admin.post('agent-admin/lotteries', form_data, function (res) {
          location.hash = '/lottery/index'
        })
        return false;
      });

      //# STEP 2
      //加载奖品列表
      let awards = []
      if (lottery.awards) {
        lottery.awards.forEach((item) => {
          awards[item.id] = item
        })
      }
      let renderAwards = function () {
        table.render({
          elem: '#lottery_awards'
          , height: 312
          , data: Object.values(awards)
          , cols: [[ //表头
            {templet: '#tpl_name', title: '名称', minWidth: 80, sort: true}
            , {field: 'level', title: '等级', width: 80}
            , {field: 'amount', title: '数量', width: 80}
            , {templet: '#tpl_rate', title: '中奖率', width: 80, align: "center"}
            , {templet: '#tpl_user_limit', title: '中奖次数', width: 100, align: "center"}
            , {title: '操作', width: 150, align: 'left', fixed: 'right', toolbar: '#tpl_tool'}
          ]]
        });
        table.on('tool(lottery_awards)', function (obj) {
          let data = obj.data
          if (lottery.status && lottery.status.value === 'enabled') {
            layer.msg('活动开启状态下禁止编辑奖品')
            return false
          }
          if (obj.event === 'del') {
            layer.confirm('确认删除该数据?', function (index) {
              delete awards[data.id]
              obj.del()
              layer.close(index)
            });
          }
          if (obj.event === 'edit') {
            showAwardForm(data)
          }
        })
      }

      $('#btn_add_award').click(function () {
        if (lottery.status && lottery.status.value === 'enabled') {
          layer.msg('活动开启状态下禁止编辑奖品')
          return false
        }
        showAwardForm()
        return false;
      })

      //奖品编辑
      function showAwardForm(data) {
        data = data || {};
        let minWidth = '800px';
        let minHeight = '800px';
        admin.popup({
          title: (data.id ? '编辑' : '添加') + '奖品'
          , area: [minWidth, minHeight]
          , id: 'popup_award'
          , success: function (layero, index) {
            view(this.id).render('lottery/award_form', data).done(function () {
              form.on('submit(submit_award)', function (d) {
                let field = d.field
                if (!field.logo_url) {
                  layer.tips('请上传奖品图片', $('#logo_url'))
                  return false
                }
                if (!field.description) {
                  layer.tips('请填写奖品说明', $('#award_desc'));
                  return false;
                }
                if (getByteLen(field.name) > 12) {
                  layer.msg('奖品名称的最大长度为6个汉字或12个数字和字母')
                  return false;
                }
                field.id = field.id || Date.now()
                awards[field.id] = field
                renderAwards()
                layer.close(index)
                return false;
              })
            })
          }
        })
      }

      function getByteLen(val) {
        let len = 0;
        for (let i = 0; i < val.length; i++) {
          const code = val.charCodeAt(i);
          if (code >= 0x0000 && code <= 0x00FF) {
            len += 1;
          } else {
            len += 2;
          }
        }
        return len;
      }

      $('.pre').click(function () {
        step.pre('#stepForm');
      });
    })
  }
</script>
